package main

import (
	pb "ihos/ihos"
)

type vip struct {
	id           int32  //PK
	name         string //姓名
	age          int32  //年龄
	phone        string //电话
	bingshi      string //病史
	address      string //地址
	status       string //状态
	comment      string //注释
	shenfenzheng string //身份证
	isvip        bool   //是否是VIP用户
}

func (d *vip) GetFromDB(id int32) error {
	sql := "SELECT id,name,age,phone,bingshi,address,status,comment,shenfenzheng,isvip FROM vip WHERE id=$1"
	return DBConn.db.QueryRow(sql, id).Scan(&d.id, &d.name, &d.age, &d.phone, &d.bingshi, &d.address, &d.status, &d.comment, &d.shenfenzheng, &d.isvip)
}

func (d *vip) GetFromDBByName(name string) error {
	sql := "SELECT id,name,age,phone,bingshi,address,status,comment,shenfenzheng,isvip FROM vip WHERE name=$1"
	return DBConn.db.QueryRow(sql, name).Scan(&d.id, &d.name, &d.age, &d.phone, &d.bingshi, &d.address, &d.status, &d.comment, &d.shenfenzheng, &d.isvip)
}

func (d *vip) GetFromDBBySFZ(sfz string) error {
	sql := "SELECT id,name,age,phone,bingshi,address,status,comment,shenfenzheng,isvip FROM vip WHERE shenfenzheng=$1"
	return DBConn.db.QueryRow(sql, sfz).Scan(&d.id, &d.name, &d.age, &d.phone, &d.bingshi, &d.address, &d.status, &d.comment, &d.shenfenzheng, &d.isvip)
}

func (d *vip) SaveToDB(id int32) error {
	sql := ""
	var err error
	if id > 0 { //update
		sql = "UPDATE vip set name=$1,age=$2,phone=$3,bingshi=$4,address=$5,status=$6,comment=$7,shenfenzheng=$8,isvip=$9 where id=$10 RETURNING id"
		err = DBConn.db.QueryRow(sql, d.name, d.age, d.phone, d.bingshi, d.address, d.status, d.comment, d.shenfenzheng, d.isvip, d.id).Scan(&d.id)
	} else { //insert
		sql = "INSERT INTO vip(name,age,phone,bingshi,address,status,comment,shenfenzheng,isvip)VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) RETURNING id"
		err = DBConn.db.QueryRow(sql, d.name, d.age, d.phone, d.bingshi, d.address, d.status, d.comment, d.shenfenzheng, d.isvip).Scan(&d.id)
	}
	return err
}

func (w *vip) toPB() *pb.Vip {
	p := &pb.Vip{
		ID:           w.id,
		Name:         w.name,
		Age:          w.age,
		Phone:        w.phone,
		Bingshi:      w.bingshi,
		Address:      w.address,
		Status:       w.status,
		Comment:      w.comment,
		Shenfenzheng: w.shenfenzheng,
		IsVip:        w.isvip,
	}
	return p
}

func (w *vip) fromPB(p *pb.Vip) *vip {
	w.id = p.GetID()
	w.name = p.GetName()
	w.age = p.GetAge()
	w.phone = p.GetPhone()
	w.bingshi = p.GetBingshi()
	w.address = p.GetAddress()
	w.status = p.GetStatus()
	w.comment = p.GetComment()
	w.shenfenzheng = p.GetShenfenzheng()
	w.isvip = p.GetIsVip()
	return w
}
